<?php


namespace app\controller;

use app\library\Excel;
use app\model\AlbumPeople;
use app\model\AlbumPhoto;
use app\process\CalFeature;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\facade\Db;
use think\facade\Log;

/**
 * 相册
 * @package app\controller
 */
class Albums extends BackendController{
    protected $model = null;
    protected $noNeedLogin = ['export_all','export_stranger'];
    protected $noNeedRight=['*'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\model\Albums();
    }

    public function after_index($lists){
        $_photo=new AlbumPhoto();
        foreach ($lists as &$list) {
            $list['count']=$_photo->where('album_id',$list['id'])->count();
        }
        return $lists;

    }

    /**
     * 保存相册下图片，然后使用job/get_albul_photo_feature方法进行计算特征值。
     * @param $album_id
     * @param $photo
     * @param $name
     * @param $idcard
     * @param $address
     * @param $contact_name
     * @param $contact_tel
     * @param $tags
     * @return void
     */
    public function add_photo($album_id,$photo,$name,$idcard,$address='',$contact_name='',$contact_tel='',$tags=''){
        $album=$this->model->find($album_id);
        if($album){
            $config=config('capture.Local');
            $create_at=date('Y-m-d H:i:s');
            $file_path=$config['capture_path'].'/album/'.$album_id.'/'.date('Ym').'/'.date('d').'/';
            $feature_status=0;
            $info=compact("album_id","name","idcard","address","contact_name","contact_tel","file_path","create_at","feature_status","tags");
            $photos=AlbumPhoto::create($info);
            save_base_img($photos->id,$photo,$file_path);
            /*$file_path.=$photos->id.'.jpg';
            $album_people=compact("name","idcard","address","contact_name","contact_tel","file_path","create_at");
            $album_people=array_merge($album_people,['photo_id'=>$photos->id,'album_id'=>$album_id]);
            AlbumPeople::create($album_people);*/
            $this->success();
        }

    }

    public function export_all($album_id,$time=0,$album_photo_id=0,$start_time='',$end_time=''){
        $album=$this->model->find($album_id);
        $_photo=new AlbumPhoto();
        $photo_ids=$_photo->where('album_id',$album_id)->column('people_id');
        //Log::info($album_id.":::photo_ids".json_encode($photo_ids));
        if($album_photo_id){
            $photo_ids=[];
            $photo_ids[]=$album_photo_id;
        }
        $header=[
            ['id','id'],
            ['姓名','name'],
            ['身份证号','idcard'],
            ['地址','address'],
            ['联系人','contact_name'],
            ['联系电话','contact_tel'],
            ['标签','tags'],
            ['抓拍机','device_name'],
            ['抓拍时间','capture_time']
        ];
        if($photo_ids){
            $_face=new \app\model\Faces();
            $now=time();
            $photos=$_photo->where('album_id',$album_id)->column('*','people_id');
            //Log::info($album_id.":::photos".json_encode($photos));
            if($time){
                $start_time=$now-3600*24*$time;
                $end_time=$now;
            }
            $faces=$_face->where('photo_id','in',$photo_ids)->whereBetweenTime('create_time',$start_time,$end_time)->field('photo_id,create_time,device_id')->order('photo_id asc,create_time desc')->select();
            //Log::info($album_id.":::faces".json_encode($faces));
            $_device=new \app\model\ViidDevice();
            $devices=$_device->column('name','device_id');
            $_tag=new \app\model\AlbumTag();
            $tags=$_tag->column('name','id');
            $list=[];
            foreach ($faces as $face) {
                $temp_photo=$photos[$face['photo_id']];
                if($temp_photo){
                    $temp['id']=$temp_photo['id'];
                    $temp['name']=$temp_photo['name'];
                    $temp['idcard']=$temp_photo['idcard'].' ';
                    $temp['address']=$temp_photo['address'];
                    $temp['contact_name']=$temp_photo['contact_name'];
                    $temp['contact_tel']=$temp_photo['contact_tel'];
                    if($temp_photo['tags']){
                        $tag_name=[];
                        $temp_tags=explode(",",$temp_photo['tags']);
                        foreach ($temp_tags as $tag) {
                            $tag_name[]=$tags[$tag];
                        }
                        $temp['tags']=implode(",",$tag_name);
                    }else{
                        $temp['tags']='';
                    }
                    $temp['device_name']=$devices[$face['device_id']];
                    $temp['capture_time']=$face['create_time'];
                    $list[]=$temp;
                }
            }
        }
        $fileName=$album['name'].'_';
        if($album_photo_id){
            $fileName.=$temp_photo['name'];
        }
        $fileName.=date('YmdHis');
        /*var_dump($list);
        var_dump($header);
        var_dump($fileName);*/
        return Excel::export( $header,true,$list, $fileName);
    }
    public function export_stranger($album_id,$time=0,$album_photo_id=0,$start_time='',$end_time='',$is_show=1,$page=1,$limit=10,$show_time=2){
        $album=$this->model->find($album_id);
        if(!$album['label_id']){
            $this->error('该底库没有标签');
        }
        $_device=new \app\model\ViidDevice();
        $device_ids=$_device->whereFindInSet('label_ids',$album['label_id'])->column('device_id');
        if(!$device_ids){
            $this->error('标签下没有相机');
        }
        $_photo=new AlbumPhoto();
        $photo_ids=$_photo->where('album_id',$album_id)->column('people_id');
        if($album_photo_id){
            $photo_ids=[];
            $photo_ids[]=$album_photo_id;
        }

        if($photo_ids){
            $_face=new \app\model\Faces();
            $now=time();
            //$photos=$_photo->where('album_id',$album_id)->column('*','people_id');
            if($time){
                $start_time=$now-3600*24*$time;
                $end_time=$now;
            }
            $ids=$_face->where('photo_id','>','0')
                ->whereNotIn('photo_id',$photo_ids)
                ->whereIn('device_id',$device_ids)
                ->whereBetweenTime('create_time',$start_time,$end_time)
                ->group('photo_id')
                ->having('count(*)>'.$show_time)
                ->column('photo_id');
            $faces=$_face->whereIn('device_id',$device_ids)
                ->whereIn('photo_id',$ids)
                ->limit($page,$limit)
                ->field('id,device_name, aizone_name, album_id, photo_id, scores, create_time, file_path')
                ->select();
            /*//$faces=$_face->where('photo_id','in',$photo_ids)->whereBetweenTime('create_time',$start_time,$end_time)->field('photo_id,create_time,device_id,file_path,scores')->order('photo_id asc,create_time desc')->page($page,$limit)->select();
            $sql=" SELECT id, device_name, aizone_name, album_id, photo_id, scores, create_time, file_path
                    FROM tp_faces
                    WHERE photo_id > 0
                      AND create_time BETWEEN '".$start_time."' AND '".$end_time."'
                      AND photo_id IN (
                          SELECT photo_id
                          FROM tp_faces
                          WHERE photo_id in (".implode(",",$photo_ids).")
                            AND create_time BETWEEN '".$start_time."' AND '".$end_time."'
                          GROUP BY photo_id
                          HAVING COUNT(*) >= ".$show_time."
                      )
                    ORDER BY photo_id
                    LIMIT ".($page-1)*$limit.','.$limit;
            //echo $sql;
            $faces=Db::query($sql);*/
            //var_dump(count($faces));die();
            /*$_device=new \app\model\ViidDevice();
            $devices=$_device->column('name','device_id');*/
            $counts=[];
            foreach ($faces as $face) {
                //$temp_photo=$photos[$face['photo_id']];
                $temp['id']=$face['id'];
                $temp['photo_id']=$face['photo_id'];
                $counts[$face['photo_id']][]=$face['id'];
                //$temp['device_name']=$devices[$face['device_id']];
                $temp['device_name']=$face['device_name'];
                $temp['capture_time']=$face['create_time'];
                $temp['scores']=$face['scores'];
                $temp['image']=$face['file_path'];
                $list[]=$temp;
            }
        }
        if(!$is_show){
            $newExcel = new Spreadsheet();


            //获取当前操作sheet的对象
            $objActSheet = $newExcel->getActiveSheet();

            //设置当前sheet的标题
            $objActSheet->setTitle('图片');
            $letter = explode(',', "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O");
            $arrHeader = array('id','姓名', '抓拍机','抓拍时间','评分','图片','小计');
            //填充表头信息
            $lenth = count($arrHeader);
            for ($i = 0; $i < $lenth; $i++) {
                $objActSheet->setCellValue("$letter[$i]1", "$arrHeader[$i]");
            };
            $temp_photo_id=0;
            //填充表格信息
            foreach ($faces as $k => $v) {
                $k += 2;
                $newExcel->getActiveSheet()->getRowDimension($k)->setRowHeight(65);
                //表格内容
                $objActSheet->setCellValue('A' . $k, $v['photo_id']);
                $objActSheet->setCellValue('B' . $k, '陌生人'.$v['photo_id']);
                $objActSheet->setCellValue('C' . $k, $v['device_name']);
                $objActSheet->setCellValue('D' . $k, $v['create_time']);
                $objActSheet->setCellValue('E' . $k, $v['scores']);

                // 图片生成
                if(!empty($v['file_path'])){
                    $img = "http://117.175.127.121:8073";
                    $drawing[$k] = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                    //$drawing[$k]->setPath(str_replace('/mnt/public/user-capture-photos',$img,$v['file_path']).$v['id'].'_face.jpg');
                    $drawing[$k]->setPath($v['file_path'].$v['id'].'_face.jpg');
                    $drawing[$k]->setWidth(80);
                    $drawing[$k]->setHeight(80);
                    $drawing[$k]->setCoordinates('F' . $k);
                    $drawing[$k]->setOffsetX(0);
                    $drawing[$k]->setOffsetY(0);
                    $drawing[$k]->setWorksheet($newExcel->getActiveSheet());

                }
                if($v['photo_id']!=$temp_photo_id){
                    $objActSheet->setCellValue('G' . $k, count($counts[$v['photo_id']]));
                    $temp_photo_id=$v['photo_id'];
                }
                // 表格高度
                //$objActSheet->getRowDimension($k)->setRowHeight(20);
            }

            $width = array(10, 20, 20, 20, 8, 20);
            //设置表格的宽度
            $objActSheet->getColumnDimension('A')->setWidth($width[0]);
            $objActSheet->getColumnDimension('B')->setWidth($width[1]);
            $objActSheet->getColumnDimension('C')->setWidth($width[2]);
            $objActSheet->getColumnDimension('D')->setWidth($width[3]);
            $objActSheet->getColumnDimension('E')->setWidth($width[4]);
            $objActSheet->getColumnDimension('F')->setWidth($width[5]);
            /*$outfile = date('Y-m-d') . ".xlsx";

            $filename = '课程分类';*/
            $fileName=$album['name'].'_';
            /*if($album_photo_id){
                $fileName.=$temp_photo['name'];
            }*/
            $fileName.=date('YmdHis');
            ob_end_clean();
            $format = 'Xlsx';

            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

            header("Content-Disposition: attachment;filename=" . $fileName .'.'. $format);

            header('Cache-Control: max-age=0');

            $objWriter = IOFactory::createWriter($newExcel, $format);

            $objWriter->save('php://output');

        }else{

            $this->success("获取成功",$list);
        }
    }

    public static function download($url,$path='images/')
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,30);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//信任任何证书
        $file = curl_exec($ch);
        curl_close($ch);
        $url = preg_replace('/\/\d+x\d+\/\d+/', '', $url);
        $filename = pathinfo($url,PATHINFO_BASENAME);
        $resource = fopen($path.$filename,'a');
        fwrite($resource, $file);
        fclose($resource);
        return $filename;
    }
}